//
//  ProgramaViewController.m
//  花花时尚
//
//  Created by 霍文轩 on 15/8/27.
//  Copyright (c) 2015年 霍文轩. All rights reserved.
//

/*
 * 热门栏目
 *
 */

#import "ProgramaViewController.h"
#import "AsyncGETConnection.h"
#import "ProgramaCollectionCell.h"
#import "ProgramaLayout.h"
#import "ProgramaModel.h"
#import "SingleProgrameViewController.h"

#import "Define.h"
#import "NightMode.h"

#import "NetWorkNotify.h"
#import "GiFHUD.h"

@interface ProgramaViewController () <UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
@property (nonatomic,retain) NSMutableArray * collectionArray;
@property (nonatomic,retain) UICollectionView * collection;
@end

@implementation ProgramaViewController
-(void)dealloc{
    [_collection release];
    [_collectionArray release];
    [super dealloc];
}
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if(self){
        self.collectionArray = [NSMutableArray array];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [GiFHUD setGifWithImageName:@"33333333333.gif"];
    UIImage * backImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NightMode nightModeON]?@"back":@"back_light" ofType:@"png"]];
    self.view.backgroundColor = [UIColor colorWithPatternImage:backImage];
    [self loadModelFromLocal];
}
// 首先从文件夹读取
-(void)loadModelFromLocal{
    NSString * path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
    NSArray * listArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[NSString stringWithFormat:@"%@/programa",path] error:nil];
    for (NSString * fileName in listArray) { // fileName为每个文件的文件名
        NSData * data = [NSData dataWithContentsOfFile:[NSString stringWithFormat:@"%@/programa/%@",path,fileName]];
        ProgramaModel * model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
        [_collectionArray addObject:model];
    }
    
    [self createCollection];
    [self reloadDataFromNetwork];
}
// 如果没有网，显示没有网络
-(void)showNetworkNotifyView{
    for (UIView * view in [self.view subviews]) {
        // 如果父视图中有mb，则删除mb，显示没网，并直接返回，如果没有，不进行任何操作
        if([view isKindOfClass:[GiFHUD class]]){
            [view removeFromSuperview];
            [self.view addSubview: [NetWorkNotify showNetworkNotify]];
            return;
        }
    }
    
}
-(void)reloadDataFromNetwork{
//    MBProgressHUD * mb = [[MBProgressHUD alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
//    [self.view addSubview:mb];
//    mb.userInteractionEnabled = NO;
//    mb.labelText = @"加载中...";
//    [mb show:YES];
    // 8秒后如果mb还在父视图，就说明没加载出来，那么显示没有网络，并从父视图删除
    [GiFHUD show];
    
    [NSTimer scheduledTimerWithTimeInterval:8 target:self selector:@selector(showNetworkNotifyView) userInfo:nil repeats:NO];
//    [mb release];
    
    [AsyncGETConnection asyncConnectionWithURLString:@"http://mrosevision.sinaapp.com/mfashion_api_v200.php?ac=getboardlistbyid&did=640%2C1136%2CiPhone5%2C2&id=fashionboard&format=json&dim=02%3A00%3A00%3A00%3A00%3A00&dic=AppStore&div=2.1.0&djb=1&diu=0F607264FC6318A92B9E13C65DB7CD3C" parmaters:nil block:^(NSData *data) {
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        
//        [mb removeFromSuperview];
        
        [self.collectionArray removeAllObjects];
        
        NSInteger i = 0;
        for (NSDictionary * subDic in [dic objectForKey:@"list"]) {
            ProgramaModel * model = [[ProgramaModel alloc] init];
            [model setValuesForKeysWithDictionary:subDic];
            [self.collectionArray addObject:model];
            
            // 存入文件
            NSString * path = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) firstObject];
            NSData * data = [NSKeyedArchiver archivedDataWithRootObject:model];
            path = [NSString stringWithFormat:@"%@/programa/%.2ld",path,(long)i]; // 要按照加入的顺序命名，而不能按照id命名，会造成读取顺序不一致
            [data writeToFile:path atomically:YES];
            i++;
            [GiFHUD dismiss];
            [model release];
        }
        
        [_collection reloadData];
    }];
}
-(void)createCollection{
    ProgramaLayout * layout = [[[ProgramaLayout alloc] init] autorelease];
    
    self.collection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-20-49+10) collectionViewLayout:layout];
    _collection.backgroundColor = [UIColor clearColor];
    _collection.delegate = self;
    _collection.dataSource = self;
    _collection.bounces = YES;
    _collection.showsVerticalScrollIndicator = NO;
    [_collection registerClass:[ProgramaCollectionCell class] forCellWithReuseIdentifier:@"cell"];
    
    [self.view addSubview:_collection];
    [_collection release];
}
#pragma  mark - UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return  _collectionArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    ProgramaCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    [cell setCellWithModel:[_collectionArray objectAtIndex:indexPath.item]];
    return  cell;
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ProgramaModel * model = [_collectionArray objectAtIndex:indexPath.item];
    SingleProgrameViewController * single = [[SingleProgrameViewController alloc] initWithId:model.id];
    [self presentViewController:single animated:YES completion:^{
        
    }];
    [single release];
}
-(void)viewWillAppear:(BOOL)animated{
    [self.view setNeedsDisplay];
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBar.hidden = YES;
    UIImage * backImage = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:[NightMode nightModeON]?@"back":@"back_light" ofType:@"png"]];
    self.view.backgroundColor = [UIColor colorWithPatternImage:backImage];
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return [NightMode nightModeON]?UIStatusBarStyleLightContent:UIStatusBarStyleDefault;
}
@end
